<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Add Curriculum</title>
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" href="css/validation.css" />
	<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css"/>
	<link rel="stylesheet" type="text/css" href="css/table-no-header.css" />
    
	<script type="text/javascript" src="js/livevalidation_standalone.js"></script> 
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	
	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>
	
<script type="text/javascript">


</script>
	
</head>
<body>


<%
	//Get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////
	//GET PERMISSION
	String name = String.valueOf(session.getAttribute("name"));
	String surname = String.valueOf(session.getAttribute("surname"));
	String role_name = String.valueOf(session.getAttribute("curriculum_role"));
	
	String department_id = String.valueOf(session.getAttribute("department_id"));
			
	System.out.println("name : " + name);///////////////////////////////
	System.out.println("department_id : " + department_id);/////////////////////////
	
	List<String> system_name = new ArrayList<String>();
	
	Permission permission = new Permission(strUser,name);
	permission.setDepartmentId(department_id);
	permission.setCurriculumCreate(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_create"))));
	permission.setCurriculumDelete(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_delete"))));
	permission.setCurriculumRead(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_read"))));
	permission.setCurriculumUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("curriculum_update"))));
	
	String permiss = "";
	if(permission.getCurriculumCreate()) {
		permiss = permiss + "Add";
	}
	if(permission.getCurriculumUpdate()) {
		if("".equals(permiss)) {
			permiss = permiss + "Edit";
		} else {
			permiss = permiss + " Edit";
		}
	}
	if(permission.getCurriculumRead()) {
		if("".equals(permiss)) {
			permiss = permiss + "Read";
		} else {
			permiss = permiss + " Read";
		}
	}
	if(permission.getCurriculumDelete()) {
		if("".equals(permiss)) {
			permiss = permiss + "Delete";
		} else {
			permiss = permiss + " Delete";
		}
	}
	///////////////////////////////////////////////////////////////////////////////////////////////////////////
	//check permission
	if(!permission.getCurriculumCreate()){%>
		<script>alert("This user dont have PERMISSION to access this zone.");</script>
		<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=curriculum_home.jsp"> 	
	<%}
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////
	//set Database Connection
		String hostProps = "";
		String usernameProps  = "";
		String passwordProps  = "";
		String databaseProps = "";
	
		try {
			//get current path
			ServletContext servletContext = request.getSession().getServletContext();
			
			InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
			Properties props = new Properties();
			
			props.load(input);

			hostProps  = props.getProperty("host");
			usernameProps  = props.getProperty("username");
			passwordProps  = props.getProperty("password");
			databaseProps = props.getProperty("database");
		} catch (Exception e) { 
			out.println(e);  
		}
		
		System.out.println("hostProperties : "+hostProps);////////////////try/////////////////
		System.out.println("usernameProperties : "+usernameProps);////////////////try/////////////////
		System.out.println("passwordProperties : "+passwordProps);////////////////try/////////////////
		System.out.println("databaseProperties : "+databaseProps);////////////////try/////////////////
		// connect database
		Connection connect = null;		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		
			connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
					"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620");//////"&characterEncoding=tis620" Encoding Thai);
		
			if(connect != null){
				System.out.println("Database Connect Sucesses.");
			} else {
				System.out.println("Database Connect Failed.");	
			}

		} catch (Exception e) {
			out.println(e.getMessage());
			e.printStackTrace();
		}
		
		/* find department in database */
		List<Department> department = new ArrayList<Department>();
		
		try {			   
			ResultSet rs_department;
			if(("0").equals(department_id)){//all department
				rs_department  = connect.createStatement().executeQuery("SELECT department_id, department_name_th" 
					+ " FROM department " + " ORDER BY department_id");
			}else{
				
				rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th "				
						+ " FROM department " 					
					    +" WHERE department_id="+permission.getDepartment_id());
				
			}
			
			while(rs_department.next()) {
				Department dep2 = new Department();
				
				dep2.setDepartmentNameTH(rs_department.getString("department_name_th"));
				dep2.setDepartmentId(Integer.parseInt(rs_department.getString("department_id")));
				department.add(dep2);
				
				department.size();
				
				System.out.println("department.size(): "+department.size());
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		

%>

	<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right" ><label><font size="4" color="#FFFFFF">  username : <%=strUser %>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>							
				</tr>
			</table>
		    <table border="0">
						<tr style="font-size:10px">
							<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
								<center><a href="curriculum_home.jsp"><h2><label style="cursor: pointer;">หน้าหลัก </label></h2></center>
							</td>
<%
			if(permission.getCurriculumRead()) {
%>
							<td  width = "720" height="50" style= "background-color:#D0D0D0 ;">
								<center><a href="curriculum_search.jsp"><h2><label style="cursor: pointer;">ค้นหา</label></h2></a></center>
							</td>
<%
			}
			if(permission.getCurriculumCreate()) {
%>	
							<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
								<center><a href="curriculum_import.jsp"><h2><label style="cursor: pointer;">เพิ่มรายวิชา</label></h2></a></center>
							</td>
							<td  width = "720" height="50" style= "background-color:#FFFFFF; border-bottom-color: #FFFFFF; border-left-color: #FFFFFF;">
								<center><h2><label></label>เพิ่มหลักสูตรใหม่</h2></a></center>
							</td>
							<td  width = "720" height="50" style= "background-color:#D0D0D0 ;">
								<center><a href="curriculum_modified_home.jsp"><h2><label style="cursor: pointer;">ปรับปรุงหลักสูตร</label></h2></a></center>
							</td>
<%
			}
			if(permission.getCurriculumUpdate()) {
%>
							<td  width = "720" height="50" style= "background-color:#D0D0D0 ;">
								<center><a href="curriculum_edit_home.jsp"><h2><label style="cursor: pointer;">แก้ไขข้อมูลหลักสูตร</label></h2></a></center>
							</td>
<%
			}
%>
						</tr>
			</table>
			
				<div id="main-content-2">
					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					<label><font size="6">เพิ่มหลักสูตรใหม่</font></label>
				</div>
				
				<div id="main-content-ac" align="center">
					<table border="0">
						<tr style="font-size:24px">
						<form id="form1" name="form1" method="post" action="">		
									
							<td width="500" height="50">
								<label for="labelnameCurriculumTH"><font size="5"><strong>ชื่อหลักสูตร (ภาษาไทย)</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>
							</td>
							<td width="500" height="50">
								<input id="nameCurriculumTH" name="nameCurriculumTH" type="text" required style="font-size:18px" />
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td width="500" height="50">
								<label for="labelnameCurriculumEN"><font size="5"><strong>ชื่อหลักสูตร (ภาษาอังกฤษ)</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>
							</td>
							<td width="500" height="50">
								<input id="nameCurriculumEN" name="nameCurriculumEN" type="text" required style="font-size:18px" />
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td height="50">
								<label for="labelyear"><font size="5"><strong>ปี พ.ศ.ของหลักสูตร</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>
							</td>
							<td height="50">
								<input id="year" name="year" type="text" maxlength="4" required style="font-size:18px" />
							</td>
						</tr>	
											
						<tr style="font-size:24px">
							<td width="500" height="50">
								<label for="labelnameDegreeTH"><font size="5"><strong>ชื่อปริญญา (ภาษาไทย)</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>
							</td>
							<td width="500" height="50">
								<input id="nameDegreeTH" name="nameDegreeTH" type="text" required style="font-size:18px" />
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td width="500" height="50">
								<label for="labelnameDegreeEN"><font size="5"><strong>ชื่อปริญญา (ภาษาอังกฤษ)</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>
							</td>
							<td width="500" height="50">
								<input id="nameDegreeEN" name="nameDegreeEN" type="text" required style="font-size:18px" />
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td width="500" height="50">
								<label for="labeldepartment"><font size="5"><strong>ภาควิชา</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>
							</td>
						<td>
							<select name="department" id="department" required style="font-size:18px">
								
							<%
							////////////////////////////// SPECIFIC Department ID//////////////////////////////
							int temppo = Integer.parseInt(permission.getDepartment_id());
							
							
							for(Department dept : department) {		
								if(dept.getDepartmentId() == 0) {
							%>
									<option value="select">Select</option>
							<% 
								}
								else {
							%>
								<option value="<%=dept.getDepartmentId()%>" id="<%=dept.getDepartmentId()%>"><%=dept.getDepartmentNameTH()%></option>										
							<%		
								}
							}
							%>
							</select>
						</td>
						</tr>
						
						<tr style="font-size:24px">
							<td height="50">
								<label for="labelcredit"><font size="5"><strong>จำนวนหน่วยกิต</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>
							</td>
							<td height="50">
								<input id= "Credit_curriculum" name="Credit_curriculum" maxlength="3" required type="text" />
							</td>
						</tr>	

						<tr style="font-size:24px">
							<td height="50">
								<label for="labelCoorganizer"><font size="5"><strong>หลักสูตรความร่วมมือ</strong></font></label>
							</td>
							<td height="50">
								<input id="Coorganizer" name="Coorganizer" type="text" style="font-size:18px" />
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td height="50">
								<label for="labelDegree"><font size="5"><strong>ระดับปริญญา</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>	  
							</td>
							<td height="50">				
						<select id="Degree" name="Degree" required style="font-size:18px">
  								<option value="">Select</option>
  								<option value="1">ปริญญาตรี</option>
								<option value="2">ปริญญาโท</option>
								<option value="3">ปริญญาเอก</option>								
						</select>
						
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td height="50">
								<label for="labelProgram"><font size="5"><strong>ประเภทของหลักสูตร</strong></font></label>
								<label><font size="5" color="#FF0000">*</font></label>
							</td>
							<td height="50">
						<select id="Program" name="Program" required style="font-size:18px" >
								<option value="">Select</option>
								<option value="1">ปกติ</option>
								<option value="2">นานาชาติ</option>								
						</select>
							  
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td height="50">
								<label for="labelOHCE"><font size="5"><strong>วันที่สำนักงานคณะกรรมการอุดมศึกษารับรอง</strong></font></label>
							</td>
							<td height="50">
								<input id="OHCE" name="OHCE" type="date" style="font-size:18px" />
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td height="50">
								<label for="labelONEC"><font size="5"><strong>วันที่สภามหาวิทยาลัยมหิดลรับรอง</strong></font></label>
							</td>
							<td height="50">
								<input id="ONEC" name="ONEC" type="date" style="font-size:18px" />
							</td>
						</tr>

						<tr style="font-size:24px">
							<td height="50">
								<label for="labelEngApp"><font size="5"><strong>วันที่สภาวิศวกรรับรอง</strong></font></label>
							</td>
							<td height="50">
								<input id="EngApp" name="EngApp" type="date" style="font-size:18px" />
							</td>
						</tr>
						
						<tr style="font-size:24px">
							<td height="50">
								<font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font>
							</td>
							<td height="50">
							</td>
						</tr>
					<tr>
						<td>
							<center><input type="submit" value="save" name="save"class="buttonStyle"/></center>																			
					</form>
						</td>
						<td>
							<center><a href="curriculum_home.jsp"><button class="buttonStyle">cancel</button></a></center>							
						</td>
					</tr>						
					</table>
				
				
				<div style="clear: both;"></div>
					<div id="footer"></div>
		</div>	
					<div style="clear: both;"></div>
			</div>			
    </div>   
   
<%
		String checkButton = request.getParameter("save");
		System.out.println(checkButton);
		
		// check save button is pressed
		if("save".equals(checkButton)) {	
			
				request.setCharacterEncoding("UTF-8");
				String  tempOHCE = null;
				String  tempONEC = null;
				String  tempEngApp = null;
				
				// get value from tag
				String CurriculumNameTH = new String(request.getParameter("nameCurriculumTH").getBytes("ISO8859_1"),"UTF-8");
				String CurriculumNameEN = request.getParameter("nameCurriculumEN");
				String BachelorNameTH = new String(request.getParameter("nameDegreeTH").getBytes("ISO8859_1"),"UTF-8");
				String BachelorNameEN = request.getParameter("nameDegreeEN");
				String Credit = request.getParameter("Credit_curriculum");
				String Year = request.getParameter("year");
				int tempyear = Integer.parseInt(Year);
				int DepartmentId = Integer.parseInt((request.getParameter("department")));
				String Coorganizer = request.getParameter("Coorganizer");
				
				String Degree = null;
				int degree = Integer.parseInt(request.getParameter("Degree"));
				if(degree == 1){Degree = "ปริญญาตรี";}
				else if(degree == 2){Degree = "ปริญญาโท";}
				else if(degree == 3){Degree = "ปริญญาเอก";}
		
				String Program = null;
				int program = Integer.parseInt(request.getParameter("Program"));
						if(program == 1){Program = "ปกติ";}
						else if(program == 2){Program = "นานาชาติ";}
				String OHCE = request.getParameter("OHCE");
				String ONEC = request.getParameter("ONEC");
				String EngApp = request.getParameter("EngApp");	
				
//////////////////////////////CHECK IF INPUT WERE SPECIAL CHARACTERS> //////////////////////
				Pattern regex = Pattern.compile("[$&+,.:;=?@#^*<>|!%]");
				Matcher matcherCurriculumNameTH = regex.matcher(CurriculumNameTH);
				Matcher matcherCurriculumNameEN = regex.matcher(CurriculumNameEN);
				Matcher matcherBachelorNameTH = regex.matcher(BachelorNameTH);
				Matcher matcherBachelorNameEN = regex.matcher(BachelorNameEN);
				Matcher matcherCredit = regex.matcher(Credit);
				Matcher matcherYear = regex.matcher(Year);
				Matcher matcherCoorganizer = regex.matcher(Coorganizer);
				
				if (matcherCurriculumNameTH.find() || matcherCurriculumNameEN.find() || matcherBachelorNameTH.find() || matcherBachelorNameEN.find() || matcherCredit.find() || matcherYear.find() || matcherCoorganizer.find()){
					%>
									<script language="javascript"> alert("ข้อมูลไม่ถูกต้อง โปรดใช้ตัวเลขหรือตัวอักษรเท่านั้น");	</script>
					<%}else{
				
				//if input was null				
				if(OHCE.equals("")){
					tempOHCE = "null";
				}else{
					tempOHCE = "'" + request.getParameter("OHCE") + "'";
				}
				
				//if input was null
				if(ONEC.equals("")){
					tempONEC = "null";
				}else{
					tempONEC = "'" + request.getParameter("ONEC") + "'";
				}
				
				//if input was null
				if(EngApp.equals("")){
					tempEngApp = "null";
				}else{
					tempEngApp = "'" + request.getParameter("EngApp") + "'";
				}	
				
				
					if(Year.length() != 4 || !Year.matches("[-+]?\\d+(\\.\\d+)?")){// If year is not number%>
					<script>alert("กรุณาใส่ปีพ.ศ.ให้ถูกต้อง");</script>
<%					}
					else if(!Credit.matches("[-+]?\\d+(\\.\\d+)?")){%>
					<script>alert("กรุณาใส่จำนวนหน่วยกิตให้ถูกต้อง");</script>
<%					}
					else if(DepartmentId==0){%>						
					<script>alert("ภาควิชา is required");</script>
<%					}
					else if (degree == 0){%>
					<script>alert("ระดับปริญญา is required");</script>
<%					}
					else if(program == 0){%>
					<script>alert("ประเภทของหลักสูตร is required");</script>
<%					}
					else{
						try {			   
							  PreparedStatement pstmt = connect.prepareStatement("INSERT INTO `curriculum`(`curriculum_name_th`, `curriculum_name_en`, `year`, `bachelor_name_th`, `bachelor_name_en`, `department_id`, `credit`, `co_organizer`, `degree`, `program`, `ohce_approved`, `onec_approved`, `curriculum_EngApp`)" 
										+ " VALUES ('"+ CurriculumNameTH +"','"+ CurriculumNameEN +"','"+ Year +"','"+ BachelorNameTH +"','"+ BachelorNameEN +"',"+ DepartmentId +",'"+ Credit +"','"+ Coorganizer +"','"+ Degree +"','"+ Program +"',"+ tempOHCE +","+ tempONEC +","+tempEngApp+")" , Statement.RETURN_GENERATED_KEYS);  
							 	pstmt.executeUpdate();  
								ResultSet keys = pstmt.getGeneratedKeys();    
								keys.next();  
								int key = keys.getInt(1);
								
								String sql_curriculum = "INSERT INTO `curriculum`(`curriculum_name_th`, `curriculum_name_en`, `year`, `bachelor_name_th`, `bachelor_name_en`, `department_id`, `credit`, `co_organizer`, `degree`, `program`, `ohce_approved`, `onec_approved`, `curriculum_EngApp`)" 
										+ " VALUES ('"+ CurriculumNameTH +"','"+ CurriculumNameEN +"','"+ Year +"','"+ BachelorNameTH +"','"+ BachelorNameEN +"',"+ DepartmentId +",'"+ Credit +"','"+ Coorganizer +"','"+ Degree +"','"+ Program +"',"+ tempOHCE +","+ tempONEC +","+tempEngApp+")";
								
								/* Log file */
								String log_user = strUser+" add curriculum";
								Log.writeUserFile(log_user);
								Log.writeUserFile(sql_curriculum);
								
								
								
								String CurriculumId_curri = Integer.toString(key);
								String Credit_curri = Credit;
								String OHCEDATE = tempOHCE;
								String ONECDATE = tempONEC;
								String EngAppDATE = tempEngApp;
								// Storage CurId in session
								session.setAttribute("CId", CurriculumId_curri);
								session.setAttribute("CCredit", Credit_curri);
								session.setAttribute("OHCE", OHCEDATE);
								session.setAttribute("ONEC", ONECDATE);
								session.setAttribute("EngApp", EngAppDATE);
								session.setAttribute("checker", "FALSE");
								session.setAttribute("value", 0);
								
								session.setAttribute("button1", 0);
								
								System.out.println("Phase 1 Success with CurriID :"+ CurriculumId_curri);
								System.out.println("Phase 2 Success with CurriCredit :"+ Credit_curri);
								System.out.println("Phase 3 Success with OHCEDATE :"+ OHCEDATE);
								System.out.println("Phase 4 Success with ONECDATE :"+ ONECDATE);
								System.out.println("Phase 5 Success with EngApp :"+ EngAppDATE);
%>
							

								<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ");</script>	
								<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=curriculum_add_category.jsp"> 
<%
							} catch (SQLException e) {
								System.out.println("Error At Phase 1 Add CurriID:"+e);
								e.printStackTrace();
							}
					}
				
		}////////else from check special char
		}
		
		connect.close();
%>  
    
<!-- <script type="text/javascript" src="js/curriculum_add_new1_validation.js"></script>	-->

	
</body>
</html>